package edu.zut.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ContextDemoServlet", urlPatterns = {"/context"})
public class ContextDemoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        //获取一个servletContext对象,所有的servlet之间，共享这一个
        //ServletContext servletContext1 = request.getServletContext();
        ServletContext servletContext = this.getServletContext();

        Integer count = (Integer) servletContext.getAttribute("count");
        if (count == null) {
            //如果获取计算器为null,初始化
            count = 1;
        }else {
            count ++ ;
        }
        System.out.println("count = " + count);
        servletContext.setAttribute("count", count);
        response.getWriter().write("当前站点的访问次数为：" + count);


        String key = servletContext.getInitParameter("key");
    }
}
